package pr.vodafone.dao;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionException;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;



import pr.vodafone.dao.dto.Cliente;

import java.io.Reader;
import java.util.List;

public class ClienteDAO {

	private SqlSessionFactory sqlSessionFactory;
    
	private SqlSessionFactory getSqlSessionFactory()
	{
		if (sqlSessionFactory == null){
			try {				
				String resource = "conf/mybatis-config.xml";
				Reader reader = Resources.getResourceAsReader(resource);
				sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
			}catch (Exception e){
				e.printStackTrace();
			}
		}
		return sqlSessionFactory;
	}

	public Cliente getCliente(String dni)
	{			
		Cliente cli = null;
		SqlSession session = getSqlSessionFactory().openSession();
		try{
			cli = session.selectOne("getCliente", dni);
		}finally{
			session.close();
		}
		return cli;
	}
		
	public List<Cliente> getClientes() throws Exception
	{
		List<Cliente> clientes = null;
		SqlSession session = getSqlSessionFactory().openSession();
		try{
			clientes = session.selectList("getClientes");
		}finally{
			session.close();
		}
		return clientes;
	}



	public void updateCliente(String dni, String newNombre, String newDir, String newEmail)
	{
		SqlSession session = getSqlSessionFactory().openSession();
		try{
			Cliente cli = new Cliente(dni,newNombre,newDir,newEmail);
			session.update("updateCliente", cli);
			session.commit();
		}catch(SqlSessionException e){
			session.rollback();
			throw e;
		}finally{
			session.close();
		}
	}

	
}
